import appEnvironment from "@/app-environments";
import axios from "axios";

// 获取基础URL配置
export function getBaseUrlConfig() {
  const {
    networkHosts: {
      apiServer1: { fullHost },
    },
  } = appEnvironment;

  let url_pro = new URL(fullHost);
  const BASE_URL_ONLINE = import.meta.env.VITE_BASE_URL_ONLINE;
  const baseUrl = new URL(fullHost);
  const host = baseUrl.hostname;
  const mqttUrl = `ws://${host}:8083/mqtt`;
  const currentUrl = new URL(window.location.href);
  const isDomain = !/^\d+\.\d+\.\d+\.\d+$/.test(currentUrl.hostname);

  // 动态切换请求地址
  const BASE_URL = isDomain
    ? BASE_URL_ONLINE
    : `${url_pro.protocol}//${url_pro.hostname}:8090`;

  return {
    fullHost,
    BASE_URL,
    mqttUrl,
    host,
  };
}

// 视频播放的通用函数
export async function getVideoRowCommon(
  videoRow: any,
  fullHost: string,
  setVideoDialogVisible: (value: boolean) => void,
  setDialogRenderVideo: (value: boolean) => void,
  setVideoUrl: (value: string) => void,
  setVideoCameraIp: (value: string) => void,
  setVideoStartTime: (value: number) => void,
  setCameraResultsTxt: (value: any[]) => void,
  getSearchAction?: (id: string) => void
) {
  setVideoDialogVisible(true);
  setDialogRenderVideo(true);

  // 根据不同的数据结构处理视频URL
  let videoFullPath = "";
  if (videoRow.video) {
    // index.vue 的数据结构
    const { BASE_URL } = getBaseUrlConfig();
    videoFullPath = BASE_URL + videoRow.video;
    setVideoUrl(videoRow.video ? videoFullPath : "");
    setVideoCameraIp(videoRow.addr);
    setVideoStartTime(videoRow.video_start || 0);
    if (getSearchAction) {
      getSearchAction(videoRow.id);
    }
  } else if (videoRow.video_url) {
    // detail.vue 的数据结构
    videoFullPath = fullHost + videoRow.video_url;
    setVideoUrl(videoRow.video_url ? videoFullPath : "");
    setVideoCameraIp(videoRow.addr);
    setVideoStartTime(videoRow.video_start || 0);
  }

  try {
    const res = await axios.get(videoFullPath);
    setCameraResultsTxt(res.data || []);
  } catch (error) {
    console.log("获取视频数据失败:", error);
    setCameraResultsTxt([]);
  }
}
